package com.fingard.dsp.bank.directbank.bocom01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

import java.util.Date;
@Component("BOCOM01BatPayRec")
public class BOCOM01BatPayRec extends BOCOM01Base implements IBatPayRec {

    /**
     * 批量代付指令提交
     * @param p_req1988 批量代付请求对象
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        // 只支持同行对私的业务
        // 返回ATS的对象
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        try {
            if (p_req1988.reqHeader.commandCode.equals("198804")) {
                tr_code = "330003";
            } else {
                tr_code = "330002";
            }

            XmlTextWriter xmlWriter = new XmlTextWriter();//
            writeCommonHeader(xmlWriter);
            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("cert_no", p_req1988.reqBatchNO);
            req_no = p_req1988.reqBatchNO;
            xmlWriter.writeElementString("pay_acno", p_req1988.ownAct);
            xmlWriter.writeElementString("type", getBankConfig().getMapValueByKey("type_Mapping", p_req1988.useType));
            xmlWriter.writeElementString("sum", p_req1988.totalNum);
            xmlWriter.writeElementString("sum_amt", p_req1988.totalAmt);
            xmlWriter.writeElementString("pay_month", Format.Date6YearMonth.format(new Date()));
            xmlWriter.writeElementString("summary", p_req1988.abstractATS);
            xmlWriter.writeElementString("busi_no", getBankConfig().getMapValueByKey("busi_no_Mapping", p_req1988.ownAct));
            xmlWriter.writeElementString("mailflg", getBankConfig().getValueAsString("mailflg"));// 传票汇总标识。
            xmlWriter.writeStartElement("tran");
            while (p_req1988.readRecord()) {
                // p_req1988.readedDetail.recAct;
                XElement tmpXElement = new XElement("rcd", "");
                tmpXElement.addChild(new XElement("card_no", p_req1988.readedDetail.recAct));
                tmpXElement.addChild(new XElement("acname", p_req1988.readedDetail.recName));
                if (p_req1988.readedDetail.recAct.length() == 17 || p_req1988.readedDetail.recAct.length() == 19 || p_req1988.readedDetail.recAct.length() == 16) {
                    tmpXElement.addChild(new XElement("card_flag", "0"));
                } else {
                    tmpXElement.addChild(new XElement("card_flag", "1"));
                }
                tmpXElement.addChild(new XElement("amt", p_req1988.readedDetail.payAmount));
                tmpXElement.addChild(new XElement("busino", p_req1988.readedDetail.askNumber));
                tmpXElement.addChild(new XElement("summary", p_req1988.readedDetail.abstractATS + "+" + p_req1988.readedDetail.purpose));
                xmlWriter.writeXElement(tmpXElement);
            }
            xmlWriter.writeEndDocument();// 写入报文完成

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                // 解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {

                    String tmpStrParCode = tmpBkReader.getFirstText("/ap/head/particular_code");
                    String tmpStrParInfo = tmpBkReader.getFirstText("/ap/head/particular_info");

                    if (!StringHelper.isNullOrEmpty(tmpStrParCode)) {
                        retAts.respCode = "0";
                        retAts.transState = tmpStrParCode;
                        retAts.respInfo = tmpStrParInfo;
                        retAts.payInfoCode = tmpStrParCode;
                        retAts.reqSeqID = tmpBkReader.getFirstText("/ap/head/req_no");
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "/ap/head/particular_code节点为空";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1988.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;

    }

    /**
     * 批量代付状态查询
     * @param p_req1998 批量代付查询请求对象
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        // 返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        // BOCOM01Header bocom01Header = new BOCOM01Header();
        // bocom01Header.tr_code = "310200";
        tr_code = "310200";
        XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
        writeCommonHeader(xmlWriter);// 写入ICBC02通用的头部节点
        xmlWriter.writeStartElement("body");
        xmlWriter.writeElementString("query_flag", "1");
        xmlWriter.writeElementString("ogl_serial_no", p_req1998.reqBatchNO);
        xmlWriter.writeEndDocument();

        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/particular_code");
                    String tmpRetMsg = tmpBkReader.getFirstText("/ap/head/particular_info");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                        if (isActiveRetCode(tmpRetCode)) {
                            String serial_record = tmpBkReader.getFirstText("/ap/body/serial_record");
                            int FieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));
                            int RecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/record_num"));
                            java.util.List<String[]> listStrings = DealMFSText(serial_record, '|', FieldNum, RecordNum);
                            retAts.respCode = "0";
                            retAts.reqSeqID = p_req1998.reqBatchNO;
                            retAts.writeBeforeDetail();
                            if (listStrings.size() > 0) {
                                listStrings.remove(0);
                                for (String[] strings : listStrings) {
                                    // （C20）| 0
                                    // 所属月份C(6)| 1
                                    // 付款账号（C21）|2
                                    // 会计核心日期（C8）|3
                                    // 批次流水号（C8）|4
                                    // 序号（C8）|5
                                    // 付款户名（C60）| 6
                                    // 付款币种（C3）|7
                                    // 业务类型（C30）|8
                                    // 付款金额（N14，2）|9
                                    // 收款卡号(C25)| 10
                                    // 收款户名(C60)|11
                                    // 状态(C1)|12
                                    // 错误原因(C30)| 13
                                    // 业务编号（20 14
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    tmpRetDetail.payAct = strings[2];
                                    tmpRetDetail.payName = strings[6];
                                    tmpRetDetail.recName = strings[11];
                                    tmpRetDetail.recAct = strings[10];
                                    tmpRetDetail.payAmount = strings[9];
                                    tmpRetDetail.curType = convertCurToATS(strings[7]);
                                    tmpRetDetail.result = tmpRetCode + "+" + strings[12];
                                    tmpRetDetail.payInfoCode = strings[13];
                                    tmpRetDetail.postScript = strings[14];
                                    tmpRetDetail.memo = strings[13];
                                    // tmpRetDetail.usage = strings[1];
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = tmpRetMsg;
                            }

                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpRetMsg;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "节点/ap/head/particular_code为空";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req1998.reqBatchNO;
        }
        if ("-1".equals(retAts.respCode)) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }


    /**
     * 批量代扣指令提交
     * @param p_req9188 批量代扣请求对象
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
        try {
            tr_code = BOCOM01TransType.code210228;
            XmlTextWriter xmlWriter = new XmlTextWriter();//
            writeCommonHeader(xmlWriter);
            XElement tmpXElement = new XElement("body", "");
            int i = 0;
            tmpXElement.addChild(new XElement("dealNo", p_req9188.reqBatchNO));
            tmpXElement.addChild(new XElement("recAccNo", p_req9188.ownAct));
            tmpXElement.addChild(new XElement("recAccName", p_req9188.ownActName));
            String protocolNo = getBankConfig().getValueAsString("protocolNo");
            if (StringHelper.hasAnyChar(protocolNo)) {
                tmpXElement.addChild(new XElement("contractNo", protocolNo));
            } else {
                retAts.respCode = "0";
                retAts.respInfo = "config中protocolNo配置为空，请检查'protocolNo'的配置！";
                return retAts;
            }
            tmpXElement.addChild(new XElement("totalNum", p_req9188.totalNum));
            tmpXElement.addChild(new XElement("totalAmt", p_req9188.totalAmt));
            tmpXElement.addChild(new XElement("summary", p_req9188.memo));
            StringBuilder serialno = new StringBuilder();
            StringBuilder payAccNo = new StringBuilder();
            StringBuilder payAccName = new StringBuilder();
            StringBuilder tranAmt = new StringBuilder();
            StringBuilder rem = new StringBuilder();
            StringBuilder subMercNo = new StringBuilder();
            StringBuilder subMercName = new StringBuilder();
            StringBuilder addInfo = new StringBuilder();
            while (p_req9188.readRecord()) {
                i++;
                serialno.append(i).append("|");
                payAccNo.append(p_req9188.readedDetail.payAct).append("|");
                payAccName.append(p_req9188.readedDetail.payName).append("|");
                tranAmt.append(p_req9188.readedDetail.payAmount).append("|");
                rem.append(p_req9188.readedDetail.purpose).append("|");
                subMercNo.append("|");
                subMercName.append("|");
                addInfo.append(p_req9188.readedDetail.memo).append("|");
            }
            tmpXElement.addChild(new XElement("serialno", serialno.toString().substring(0, serialno.length() - 1)));
            tmpXElement.addChild(new XElement("payAccNo", payAccNo.toString().substring(0, payAccNo.length() - 1)));
            tmpXElement.addChild(new XElement("payAccName", payAccName.toString().substring(0, payAccName.length() - 1)));
            tmpXElement.addChild(new XElement("tranAmt", tranAmt.toString().substring(0, tranAmt.length() - 1)));
            tmpXElement.addChild(new XElement("rem", rem.toString().substring(0, rem.length() - 1)));
            tmpXElement.addChild(new XElement("subMercNo", subMercNo.toString().substring(0, subMercNo.length() - 1)));
            tmpXElement.addChild(new XElement("subMercName", subMercName.toString().substring(0, subMercName.length() - 1)));
            tmpXElement.addChild(new XElement("addInfo", addInfo.toString().substring(0, addInfo.length() - 1)));
            tmpXElement.addChild(new XElement("unitFlg", "0"));
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                // 解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {

                    String tmpStrParCode = tmpBkReader.getFirstText("/ap/head/particular_code");
                    String tmpStrParInfo = tmpBkReader.getFirstText("/ap/head/particular_info");

                    if (!StringHelper.isNullOrEmpty(tmpStrParCode)) {
                        retAts.respCode = "0";
                        retAts.transState = tmpStrParCode;
                        retAts.respInfo = tmpStrParInfo;
                        retAts.payInfoCode = tmpStrParCode;
                        retAts.reqSeqID = tmpBkReader.getFirstText("/ap/head/req_no");
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "/ap/head/particular_code节点为空";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req9188.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代扣状态查询
     * @param p_req9198 批量代扣查询请求对象
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9198.reqHeader);
        retAts.reqSeqID = p_req9198.reqBatchNO;
        try {
            tr_code = BOCOM01TransType.code210226;
            XmlTextWriter xmlWriter = new XmlTextWriter();//
            writeCommonHeader(xmlWriter);
            XElement tmpXElement = new XElement("body", "");
            int i = 0;
            tmpXElement.addChild(new XElement("dealNo", p_req9198.reqBatchNO));
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/particular_code");
                    String tmpRetMsg = tmpBkReader.getFirstText("/ap/head/particular_info");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                        if (isActiveRetCode(tmpRetCode)) {
                            String serial_record = tmpBkReader.getFirstText("/ap/body/serialRecord");
                            int FieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));
                            int RecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/record_num"));
                            java.util.List<String[]> listStrings = DealMFSText(serial_record, '|', FieldNum, RecordNum);
                            retAts.respCode = "0";
                            retAts.reqSeqID = p_req9198.reqBatchNO;
                            retAts.writeBeforeDetail();
                            if (listStrings.size() > 0) {
                                listStrings.remove(0);
                                for (String[] strings : listStrings) {
                                    /**
                                     收款账号|总笔数|总金额|网银批次流水号(28)|子序号（C8）|付款账号(C40)|付款账号户名(C60)|收款金额(N14.2)|备注(C120)|状态(C1)|错误信息(C100)|
                                        0   |  1  |  2  |        3        |     4     |      5     |        6       |      7       |     8    |    9  |     10
                                     */
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    tmpRetDetail.recAct = strings[0];
                                    tmpRetDetail.postScript = strings[3];
                                    tmpRetDetail.payAct = strings[5];
                                    tmpRetDetail.payName = strings[6];
                                    tmpRetDetail.payAmount = strings[7];
                                    tmpRetDetail.memo = strings[8];
                                    tmpRetDetail.result = tmpRetCode + "+" + strings[9];
                                    tmpRetDetail.payInfoCode = strings[10];
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = tmpRetMsg;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpRetMsg;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "节点/ap/head/particular_code为空";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req9198.reqBatchNO;
        }
        retAts.writeAfterDetail();
        return retAts;
    }

}
